package com.controller;

import com.annotation.RequestMapping;
import com.common.BaseController;
import com.pay.pro.OauthToken;
import com.pay.pro.WxUserInfo;
import com.pay.util.CheckUtil;
import com.pay.util.CommonUtil;
import com.pay.util.MessageUtil;
import org.dom4j.DocumentException;

import javax.servlet.ServletException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * Created by Administrator on 2016/6/2.
 */
@RequestMapping("WxInfo")
public class WxInfoController extends BaseController {
    private static  String appid  = "wxc6eb97e3b6a2c475";
    private static  String secret = "36c0a5c02af5898efd0d52856c3b32fe";
    //用户授权凭证url
    private String get_access_token_url="https://api.weixin.qq.com/sns/oauth2/access_token?" +
            "appid=APPID" + "&secret=SECRET&" + "code=CODE&grant_type=authorization_code";
    //根据用户授权凭证获取用户信息url(URL2)
    private String get_userinfo="https://api.weixin.qq.com/sns/userinfo?" +
            "access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";

    /**
     * 接收微信端用户发送数据，并返回给微信服务器
     * @throws ServletException
     * @throws IOException
     */
    public void WxSendText() throws ServletException,IOException{
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        System.out.print(request.getMethod().toString());
        if("GET".equals(request.getMethod())) {
            String signature = request.getParameter("signature");
            String timestamp = request.getParameter("timestamp");
            String nonce = request.getParameter("nonce");
            String echostr = request.getParameter("echostr");
            if (CheckUtil.checkSignature(signature, timestamp, nonce)) {
                out.print(echostr);
            }
            out.close();
        }
        String accessToken = CommonUtil.getToken(CommonUtil.token_url,appid,secret).getAccessToken();
            try {
                Map<String, String> map = MessageUtil.xmlToMap(request);
                String toUserName = map.get("ToUserName");
                String fromUserName = map.get("FromUserName");
                String createTime = map.get("CreateTime");
                String msgType = map.get("MsgType");
                String content = map.get("Content");
                String msgId = map.get("MsgId");
                String message = null;
                WxUserInfo user = CommonUtil.getUserInfo(CommonUtil.wx_get_userinfo,accessToken,fromUserName);
                if (MessageUtil.MESSAGE_TEXT.equals(msgType)) {
                    if("1".equals(content)){
                        message = MessageUtil.InitText(fromUserName,toUserName,user.getHeadImgUrl()+user.getNickname());
                    }else if("2".equals(content)){
                        message = MessageUtil.InitText(fromUserName,toUserName,toUserName);
                    }else if("?".equals(content)||"？".equals(content)){
                        message  = MessageUtil.InitText(fromUserName,toUserName,MessageUtil.menuText());
                    }
                    if(!"1".equals(content)&&!"2".equals(content)&&
                            !"?".equals(content)&&!"?".equals(content)){
                        message = MessageUtil.InitText(fromUserName,toUserName,"input error");
                    }
                    System.out.print(message);
                }else if(MessageUtil.MESSAGE_EVENT.equals(msgType)){
                    String event_type = map.get("Event");
                    if(MessageUtil.EVENT_SUBSCRIBE.equals(event_type)){
                        message  = MessageUtil.InitText(fromUserName,toUserName,MessageUtil.menuText());
                    }
                }
                out.print(message);
            } catch (DocumentException e) {
                e.printStackTrace();
            } finally {
                out.close();
            }
    }

    public void WxOauth2() throws ServletException,IOException{
        request.setCharacterEncoding("UTF-8");  //必加  否则code编码会出错
        response.setCharacterEncoding("UTF-8"); //必加  否则code编码会出错
        try {
            String code = request.getParameter("code");
            System.out.print("code:" + code);
            get_access_token_url = get_access_token_url.replace("APPID", appid);
            get_access_token_url = get_access_token_url.replace("SECRET", secret);
            get_access_token_url = get_access_token_url.replace("CODE", code);
            OauthToken token = CommonUtil.oauthToken(get_access_token_url, appid, secret);
            String accessToken = token.getAccessToken();
            String openid = token.getOpenid();
            WxUserInfo userinfoJSON = CommonUtil.getUserInfo(get_userinfo, accessToken, openid);
            String user_openid = userinfoJSON.getOpenId();
            String user_nickname = userinfoJSON.getNickname();
            String user_headimgurl = userinfoJSON.getHeadImgUrl();
            response.setContentType("text/html; charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
            out.println("<HTML>");
            out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
            out.println("  <BODY>");
            out.print("    This is ");
            out.print(this.getClass());
            out.println("openid:"+user_openid+"\n\n");
            out.println("nickname:"+user_nickname+"\n\n");
            out.println("<img src='"+user_headimgurl+"'"+"/>");
            out.println(">");
            out.println("  </BODY>");
            out.println("</HTML>");
            out.flush();
            out.close();
            out.flush();
            out.close();
        }catch (Exception e){
            response.getWriter().println(e.getMessage());
        }
    }

}
